package com.syt.cellphone.information.http

import NumberFormatUtil
import android.content.Context
import android.util.Log
import com.syt.cellphone.information.App
import com.syt.cellphone.information.R
import com.syt.cellphone.information.http.Url.baseUrl
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.catch
import kotlinx.coroutines.flow.onCompletion
import kotlinx.coroutines.flow.onStart
import okhttp3.OkHttpClient
import retrofit2.Response
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
import java.util.concurrent.TimeUnit

/**
 * @auther zhulei
 * @date : 2020/9/24 17:43
 * @description : 干活的家伙
 */
object HttpHelper {

    private const val DEFAULT_TIME = 15L

    var context: Context = App.INSTANCE

    val TAG = this.javaClass.simpleName

    val client: OkHttpClient by lazy {
        val builder = OkHttpClient.Builder()
            // 设置读取时间
            .readTimeout(DEFAULT_TIME, TimeUnit.SECONDS)
            // 请求超时时间
            .connectTimeout(DEFAULT_TIME, TimeUnit.SECONDS)
            // 设置写入超时时间
            .writeTimeout(DEFAULT_TIME, TimeUnit.SECONDS)
            .addInterceptor(LogInterceptor())
        builder.build()
    }

    inline fun <reified T> getApiService(clazz: Class<T>): T {
        return getRetrofit().create(clazz)
    }

    fun getRetrofit(): Retrofit {
        return Retrofit.Builder()
            .baseUrl(baseUrl)
            .client(client)
            .addConverterFactory(GsonConverterFactory.create())
            .build()
    }

    fun <T> checkError(response: Response<MyResponse<T>>): Result<T> {
        Log.e(TAG, "code:===" + response.code())
        Log.e(TAG, "errorBody===:" + response.errorBody())
        Log.e(TAG, "Body===:" + response.body())
        return when (response.code()) {
            200 -> {
                val body = response.body()!!
                when (body.code) {
                    200 -> Result.Success(body.data!!)
                    401 -> {
                        // 登录过期
                        Result.Failure(body.msg)
                    }
                    else -> Result.Failure(body.msg)
                }
            }
            404 -> Result.Failure("404异常")
            500 -> Result.Failure("500" + App.INSTANCE.getString(R.string.requet_error_noservice))
            502 -> Result.Failure("502" + App.INSTANCE.getString(R.string.requet_error_service))
            else -> Result.Failure(App.INSTANCE.getString(R.string.requet_error_unknow))
        }
    }

    /**
     * 统一执行的, 带弹窗的开关
     */
    fun <T> Flow<T>.next(): Flow<T> =
    onStart {
        // 显示加载
//        context.toast("开始网络请求")
    }
    .catch {
        // 失败
        Log.d(TAG, "next: $it ${NumberFormatUtil.longToString(System.currentTimeMillis())} + ${Thread.currentThread().name}")
        // 需要处理一下
        throw Exception("网络异常")
    }.onCompletion {
        // 加载完成
//        context.toast("结束网络请求")
    }

}